<template>
  <div class="login-page">
    
    <div class="login-overlay">
      <div class="login-container">
        <div class="login-header">
          <h2>用户登录</h2>
          <el-button type="text" class="close-btn" @click="$router.push('/')">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px" class="login-form" @keydown.enter="handleLogin" @keydown.esc="$router.push('/')">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" size="large">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password size="large">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <div class="captcha-row">
              <el-input v-model="loginForm.captcha" placeholder="请输入验证码" style="width: 140px;" size="large" />
              <span class="captcha-img" @click="generateCaptcha">{{ captcha }}</span>
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button class="btn-primary" type="primary" @click="handleLogin" style="width: 100%;">登录</el-button>
          </el-form-item>
          <el-form-item class="login-links">
            <el-button type="text" @click="$router.push('/register')">注册账号</el-button>
            <el-button type="text" @click="$router.push('/forgot-password')">忘记密码？</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import axiosInstance from '@/plugins/axios'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        captcha: '',
        remember: false
      },
      captcha: '',
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.generateCaptcha()
  },
  methods: {
    generateCaptcha() {
      // 简单生成4位数字验证码
      this.captcha = Math.random().toString().slice(2, 6)
    },
    handleLogin() {
      this.$refs.loginFormRef.validate((valid) => {
        if (!valid) return
        if (this.loginForm.captcha !== this.captcha) {
          ElMessage.error('验证码错误')
          this.generateCaptcha()
          return
        }
        
        // 调用后端登录API
        this.$axios.post('/user/login', {
          account: this.loginForm.username,
          password: this.loginForm.password,
          isAdmin: false
        }).then(response => {
          if (response.data.code === 1) {
            // 登录成功，保存用户信息和token
            const userData = response.data.data
            localStorage.setItem('currentUser', JSON.stringify(userData))
            localStorage.setItem('token', userData.token)
            axiosInstance.defaults.headers.common['Authorization'] = `${userData.token}`;
            ElMessage.success('登录成功')
            const redirect = this.$route.query.redirect || '/'
            this.$router.push(redirect)
          } else {
            ElMessage.error(response.data.msg || '登录失败')
            this.generateCaptcha()
          }
        }).catch(error => {
          console.error('登录失败:', error)
          ElMessage.error('登录失败，请稍后重试')
          this.generateCaptcha()
        })
      })
    }
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: var(--color-bg);
}

.login-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.login-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.15);
  min-width: 400px;
  max-width: 450px;
  animation: slideIn 0.3s ease-out;
}

@media (max-width: 768px) {
  .login-container {
    min-width: 320px;
    max-width: 90vw;
    margin: 0 1rem;
  }
  
  .login-form {
    padding: 1.5rem;
  }
  
  .login-header {
    padding: 1rem 1.5rem 0 1.5rem;
  }
  
  .login-header h2 {
    font-size: 1.3rem;
  }
}

@media (max-width: 480px) {
  .login-container {
    min-width: 280px;
    max-width: 95vw;
  }
  
  .login-form {
    padding: 1rem;
  }
  
  .login-header {
    padding: 0.8rem 1rem 0 1rem;
  }
  
  .login-header h2 {
    font-size: 1.2rem;
  }
  
  .captcha-row {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .captcha-img {
    align-self: flex-start;
  }
}

.login-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem 0 2rem;
  border-bottom: 1px solid #f0f0f0;
}

.login-header h2 {
  margin: 0;
  color: var(--color-primary);
  font-size: 1.5rem;
}

.close-btn {
  color: #999;
  font-size: 1.2rem;
}

.close-btn:hover {
  color: var(--color-primary);
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.login-form {
  padding: 2rem;
}

.btn-primary {
  height: 42px;
  font-size: 16px;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #145A32 0%, #218c5c 100%);
  border: none;
}

.login-links {
  display: flex;
  justify-content: space-between;
  margin-top: 1rem;
}
.captcha-row {
  display: flex;
  align-items: center;
  gap: 1rem;
}
.captcha-img {
  display: inline-block;
  background: #f5f5f5;
  color: #333;
  font-weight: bold;
  font-size: 1.2rem;
  padding: 0.5rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  user-select: none;
  border: 1px solid #dcdfe6;
  transition: background 0.2s;
}
.captcha-img:hover {
  background: #e0e7ff;
}
</style>
